/**
 * 客户主数据业务
 * Created by benben on 14-9-20.
 */
var Condition = require('../../utils/mongodb/Condition');
var Conditions = require('../../utils/mongodb/Conditions');
var Query = require('../../utils/mongodb/Query');
var Page = require('../../utils/page/Page');

var CustomerService = function(){
    this.model = require('../../modules/customer/customer');
};

/**
 * 保存
 * @param customer
 * @param callback
 */
CustomerService.prototype.save = function(customer,callback){
    customer.save(function(err) {
        callback(err);
    });
};

/**
 * 根据ID查询
 * @param id
 * @param callback
 */
CustomerService.prototype.getById = function(id,callback){
    this.model.findOne({ _id: id}, function(err, customer) {
        if (err) {
            callback(err);
        }
        var page = new Page({
            totalCount : 1,
            data : customer
        });
        callback(null,page);
    });
};

/**
 * 更新
 * @param id
 * @param customer
 * @param callback
 */
CustomerService.prototype.updateById = function(id,customer,callback){
    this.model.findOneAndUpdate({ _id: id }, customer, function (err){
        callback(err);
    });
};

/**
 * 分页查询
 * @param query
 * @param callback
 */
CustomerService.prototype.findPage = function(query,callback){
    var me = this;

    var conditions = me.createConditions(query.conditionObj);

    Query.findPageWithModel(me.model,conditions,query.start,query.limit,function(err,page){
        callback(err,page);
    });
};

/**
 * 根据请求创建查询条件
 * @param customer
 * @returns {Array}
 */
CustomerService.prototype.createConditions = function(customer){
    var conditions = new Conditions({
        type : 'and',
        items : []
    });

    if(customer.customerName){
        var condition = new Condition({
            type : 'like',
            name : 'customerName',
            value :  customer.customerName
        });
        conditions.items.push(condition);
    }

    if(customer.customerNo){
        var condition = new Condition({
            type : 'like',
            name : 'customerNo',
            value :  customer.customerNo
        });
        conditions.items.push(condition);
    }

    return conditions;
};

module.exports = CustomerService;